package com.atguigu.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.atguigu.oss.service.OssService;
import com.atguigu.oss.utils.ContandPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {

    @Override
    public String uploadFileAvatar(MultipartFile file) {
        String endpoint = ContandPropertiesUtils.END_POINT;
        String accessKeyId = ContandPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ContandPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ContandPropertiesUtils.BUCKET_NAME;
        String url = null;
        String filename = file.getOriginalFilename();
        //添加随机的值，生成uuid
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        //新的文件名称
        filename = uuid+filename;
        //把文件按照日期进行分类
        //2019/11/12/01.jpg
        //获取当前的日期
        String datePath = new DateTime().toString("yyyy/MM/dd");

        //拼接
        filename = datePath +"/"+filename;

        // 创建OSSClient实例。
        try {
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            InputStream inputStream = file.getInputStream();
            //获取文件名称,文件的原始名称

            System.err.println(filename);
            //第二个参数,第三个参数上传文件的输入流
            ossClient.putObject(bucketName,filename,inputStream);
            ossClient.shutdown();
            //把上传的阿里云的路径拼起来
            //https://edu--1530242.oss-cn-guangzhou.aliyuncs.com/2056185.jpg
             url = "https://"+bucketName+"."+endpoint+"/"+filename;
        } catch (Exception e) {
          e.printStackTrace();

        }finally {
            return url;
        }

    }
}
